package com.rzico.core.controller;

import com.alibaba.fastjson.JSONObject;
import com.rzico.base.BaseController;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.plugin.PaymentPlugin;
import com.rzico.util.MD5Utils;
import com.rzico.util.StringUtils;
import com.rzico.util.XMLUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by icssh on 2021/4/4.
 */
@Slf4j
public class achruController {

    public static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";

/*    static {
//		Protocol easyhttps = new Protocol("https",new MySecureProtocolSocketFactory(), 443);
        Protocol easyhttps = new Protocol("https",new MySSLProtocolSocketFactory(), 443);

        Protocol.registerProtocol("https", easyhttps);
    }*/

    public static void main(String[] args) throws Exception{
        signIn();
//        trade();
    }

    public static void trade() throws Exception{

        HashMap<String, Object> params = new HashMap<>();
        HashMap<String, Object> finalpackage = new HashMap<>();
        String createNoncestr = StringUtils.CreateNoncestr();
        params.put("merchantNo", "94734084011A01A");
        params.put("terminalNo", "26001170");
        params.put("batchNo", "");

        params.put("traceNo", "000001");
        params.put("outTradeNo", "20210404000001");
        params.put("transAmount", 1);
        params.put("appid", "");
        params.put("openId", "");
        params.put("tradeChannel", "01");
        params.put("nonceStr", createNoncestr);

        String sign = getSign(params, new SysPlugin());
        params.put("sign", sign);

        String data = JSONObject.toJSONString(params);
        String respStr = post(UNIFIED_ORDER_URL,data,null);

        log.info(respStr);
        Map resultMap = XMLUtils.xmlToMap(respStr);
        String return_code = (String) resultMap.get("return_code");

    }


    public static String signIn(){
        HashMap<String, Object> params = new HashMap<>();
        params.put("merchantNo", "94734084011A01A");
        params.put("terminalNo", "26001170");
        String data = JSONObject.toJSONString(params);
        String respStr = post("https://wxtest2.ahrcu.com:3443/cposp/pay/signIn",data,null);
        log.info("signIn == " + respStr);
        return respStr;
    }

    /**
     * 作用：生成签名
     */
    public static String getSign(HashMap<String, Object> params, SysPlugin sysPlugin) throws Exception {
        String str = joinKeyValue(params,"&",true,"sign","key") + "83ADA0138F79455B1CADAFF05249AED";

        // 签名步骤三：MD5加密 签名步骤四：所有字符转为大写
        str = MD5Utils.getMD5Str(str).toUpperCase();
        return str;
    }

    protected static String joinKeyValue(Map<String, Object> map,String separator, boolean ignoreEmptyValue, String... ignoreKeys) {
        List<String> keys = new ArrayList<String>(map.keySet());
        Collections.sort(keys);
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = ConvertUtils.convert(map.get(key));
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(key) && !ArrayUtils.contains(ignoreKeys, key) && (!ignoreEmptyValue || org.apache.commons.lang3.StringUtils.isNotEmpty(value))) {
                list.add(key + "=" + (value != null ? value : ""));
            }
        }

        return org.apache.commons.lang3.StringUtils.join(list, separator);
    }

    /**
     * POST请求
     * @param url URL
     * @param data 请求参数
     * @return 返回结果
     */
/*    public static String post(String url,String data,HttpClient httpClient1) {
        Assert.hasText(url);
        String result = null;

        HttpPost httpPost =new HttpPost(url);

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {// 通过址默认配置创建一个httpClient实例
//            httpClient = HttpClients.createDefault();
                BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
                        RegistryBuilder.<ConnectionSocketFactory>create()
                                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                                .build(),
                        null,
                        null,
                        null
                );
            httpClient = HttpClientBuilder.create()
                    .setConnectionManager(connManager)
                    .build();
            // httpClient对象执行post请求,并返回响应参数对象
            RequestConfig requestConfig = RequestConfig.custom()
                    // 连接主机服务超时时间
                    .setConnectTimeout(10000)
                    // 请求超时时间
                    .setConnectionRequestTimeout(10000)
                    // 数据读取超时时间
                    .setSocketTimeout(10000)
                    .build();
            // 为httpGet实例设置配置
            httpPost.setConfig(requestConfig);
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity, Consts.UTF_8);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (null != httpResponse) {
                    httpResponse.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }*/

    /**
     * POST请求
     * @param url URL
     * @param data 请求参数
     * @return 返回结果
     */
    public static String post(String url,String data,HttpClient httpClient) {
        Assert.hasText(url);
        String result = null;
        if (httpClient==null) {
            httpClient = new DefaultHttpClient();
        }
        try {
            HttpPost httpPost = new HttpPost(url);

            httpPost.setEntity(new StringEntity(data, "UTF-8"));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");
            EntityUtils.consume(httpEntity);
        } catch (ClientProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }
}
